package be.ac.ua.ecampus.cmat;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import be.ac.ua.ecampus.cmat.types.Entity;

@WebServlet(description = "Search", urlPatterns = { "/search" })
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public SearchServlet() {
		super();
	}
	  
	public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		final String search = request.getParameter("search");
		this.doGet(request, response);
	}
	
	public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		final String search = request.getParameter("search");
		if ((search == null) || search.isEmpty()) {
			System.out.println("[CMAT WARNING] - [SEARCH] - Empty string given.");
			return;
		}
		QueryHandler queryHandler = new QueryHandler();
		try {
			Collection<Entity> result = queryHandler.search(search);
			request.setAttribute("search", result);
	    	request.getRequestDispatcher("/showSearch.jsp").forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	
}
